﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data.Common;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using CommunityToolkit.Mvvm.Messaging;
using Serilog;
using Serilog.Core;
using SimpleTool.ActivityUnit;
using SimpleTool.Base;
using SimpleTool.SerialTool.SerialControl;
using SimpleTool.Server;
using static SimpleTool.ActivityUnit.ActivitySectionModel;
using static SimpleTool.SerialTool.SerialControl.CommandSectionModel;

namespace SimpleTool.SerialTool
{
    public class OverViewModel : Notify
    {
        public IPowerPlant PowerPlantServer;

        private readonly ILogger Logger = Log.ForContext<OverViewModel>();

        public OverViewModel(IPowerPlant PowerServer)
        {
            PowerPlantServer = PowerServer;

            WeakReferenceMessenger.Default.Register<MvvmMessage>(this, MvvmMessageProcessPlant);
        }

        public OverSectionModel HoldOverSectionModel { set; get; } = new OverSectionModel();

        public ICommand FreeContentTouchCommand
        {
            set
            {
                HoldOverSectionModel.FreeContentTouchCommand = value;
            }
            get
            {
                HoldOverSectionModel.FreeContentTouchCommand ??= new EasyCommand(FreeCommandWrite, bool () => { return true; });
                return HoldOverSectionModel.FreeContentTouchCommand;
            }
        }

        // 通知组件开始获取指令文本
        public ICommand FreeContentNotifyCommand
        {
            set
            {
                HoldOverSectionModel.FreeContentNotifyCommand = value;
            }
            get
            {
                HoldOverSectionModel.FreeContentNotifyCommand ??= new EasyCommand(FreeCommandNotifyExecute, bool () => { return true; });
                return HoldOverSectionModel.FreeContentNotifyCommand;
            }
        }

        public ICommand CmdInfoSubmitCommand
        {
            set
            {
                HoldOverSectionModel.CmdInfoSubmitCommand = value;
            }
            get
            {
                HoldOverSectionModel.CmdInfoSubmitCommand ??= new EasyCommand(EchoCommandEditUpdate, bool () => { return true; });
                return HoldOverSectionModel.CmdInfoSubmitCommand;
            }
        }

        public ICommand CmdEchoFocusCommand
        {
            set
            {
                HoldOverSectionModel.CmdEchoFocusCommand = value;
            }
            get
            {
                HoldOverSectionModel.CmdEchoFocusCommand ??= new EasyCommand(CmdEchoFocusEvent, bool () => { return true; });
                return HoldOverSectionModel.CmdEchoFocusCommand;
            }
        }

        public ICommand CmdEchoWalkCommand
        {
            set
            {
                HoldOverSectionModel.CmdEchoWalkCommand = value;
            }
            get
            {
                HoldOverSectionModel.CmdEchoWalkCommand ??= new EasyCommand(CmdEchoWalkEvent, bool () => { return true; });
                return HoldOverSectionModel.CmdEchoWalkCommand;
            }
        }

        public Visibility FreeCommandVisibility
        {
            set
            {
                HoldOverSectionModel.FreeCommandVisibility = value;
                propertyChangeSend(nameof(FreeCommandVisibility));
            }
            get
            {
                return HoldOverSectionModel.FreeCommandVisibility;
            }
        }

        public Visibility CommandEchoVisibility
        {
            set
            {
                HoldOverSectionModel.CommandEchoVisibility = value;
                propertyChangeSend(nameof(CommandEchoVisibility));
            }
            get
            {
                return HoldOverSectionModel.CommandEchoVisibility;
            }
        }


        public bool DocuContentCaptrue
        {
            set
            {
                HoldOverSectionModel.DocuContentCaptrue = value;
                propertyChangeSend(nameof(DocuContentCaptrue));
            }
            get
            {
                return HoldOverSectionModel.DocuContentCaptrue;
            }
        }

        public string DocuContentTouch
        {
            set
            {
                HoldOverSectionModel.DocuContentTouch = value;
                propertyChangeSend(nameof(DocuContentTouch));
            }
            get
            {
                return HoldOverSectionModel.DocuContentTouch;
            }
        }

        // 指令编辑组件渐变值
        public double CommandEchoOpacity
        {
            set
            {
                HoldOverSectionModel.CommandEchoOpacity = value;
                propertyChangeSend(nameof(CommandEchoOpacity));
            }
            get
            {
                return HoldOverSectionModel.CommandEchoOpacity;
            }
        }
        
        //用户组件
        public object ControlContent
        {
            set
            {
                HoldOverSectionModel.ControlContent = value;
                propertyChangeSend(nameof(ControlContent));
            }
            get
            {
                HoldOverSectionModel.ControlContent ??= new object();
                return HoldOverSectionModel.ControlContent;
            }
        }

        public AlterCommandStruct EchoCommandInfo 
        { 
            set 
            {
                HoldOverSectionModel.EchoCommandInfoStdin = value;
                propertyChangeSend(nameof(EchoCommandInfo));
            } 
            get 
            {
                return HoldOverSectionModel.EchoCommandInfoStdin;
            } 
        }

        //文本框数据
        public ObservableCollection<string> DynamicRichContent
        {
            set
            {
                HoldOverSectionModel.DynamicRichContent = value;
                propertyChangeSend(nameof(DynamicRichContent));
            }
            get
            {
                return HoldOverSectionModel.DynamicRichContent;
            }
        }

        public static void MvvmMessageProcessPlant(object recipient, MvvmMessage message)
        {
            OverViewModel self = (OverViewModel)recipient;
            switch (message.Type)
            {
                case MvvmMessage.MvvmType.Command_EditInfoGet:
                    self.UnexpectedCmdInfoEcho(message);
                    break;
            }
        }

        // 更新已编辑的指令信息
        public void EchoCommandEditUpdate(object? param)
        {
            WeakReferenceMessenger.Default.Send<MvvmMessage>(new MvvmMessage(MvvmMessage.MvvmType.Command_EditInfoSend, EchoCommandInfo));
        }

        //指令编辑组件聚焦
        public async void CmdEchoFocusEvent(object? param)
        {
            if (param is not null && bool.TryParse(param.GetSafetyChar(), out bool isGotFocus))
            {
                HoldOverSectionModel.CommandEchoisGotFocus = isGotFocus;
                await CmdEchoOpacityGradent();
            }
        }

        //指令编辑组件失焦
        public async void CmdEchoWalkEvent(object? param)
        {
            if (param is not null && bool.TryParse(param.GetSafetyChar(), out bool isWalking))
            {
                HoldOverSectionModel.CommandEchoisWalking = isWalking;
                await CmdEchoOpacityGradent();
            }
        }

        //指令组件渐变执行
        public async Task CmdEchoOpacityGradent()
        {
            if (HoldOverSectionModel.CommandEchoisWalking)
            {
                CommandEchoVisibility = Visibility.Visible;
                while (HoldOverSectionModel.CommandEchoisWalking)
                {
                    if (Math.Round(CommandEchoOpacity, 1) >= 1.0 || !HoldOverSectionModel.CommandEchoisWalking)
                    {
                        break;
                    }
                    else
                    {
                        CommandEchoOpacity += 0.1;
                    }
                    await Task.Delay(50);
                }
            }
            else
            {
                await Task.Delay(3000);
                while (!HoldOverSectionModel.CommandEchoisGotFocus && !HoldOverSectionModel.CommandEchoisWalking)
                {
                    if (Math.Round(CommandEchoOpacity, 1) <= 0.0 || HoldOverSectionModel.CommandEchoisWalking)
                    {
                        CommandEchoVisibility = Visibility.Collapsed;
                        break;
                    }
                    else
                    {
                        CommandEchoOpacity -= 0.1;
                    }
                    await Task.Delay(50);
                }
            }
        }

        // 串口数据接收
        public void SerialDataReceive(string receive)
        {
            Application.Current.Dispatcher.Invoke(() =>
            {
                string timeTemp = DateTime.Now.ToString("HH:mm:ss");
                HoldOverSectionModel.DynamicRichContent.Add($"[{timeTemp}] {receive}");
            });
        }

        // 获取右下指令信息，发送标识至组件中，组件发送文本框内容
        public void FreeCommandNotifyExecute(object? param)
        {
            DocuContentCaptrue = !DocuContentCaptrue;

            //WeakReferenceMessenger.Default.Send<MvvmMessage>(new MvvmMessage(MvvmMessage.MvvmType.RichBox_FreeCommandGet));
        }

        // 执行右下角文本框指令，可通过@分割多条指令执行
        private async void FreeCommandWrite(object? param)
        {
            Logger.DebudElite("---2222  ", param);
            string simple(string command)
            {
                string _command = Regex.Match(command, "[^\r\n]+").Value;
                if (!string.IsNullOrEmpty(_command)) _command = _command.Trim();
                return _command;
            }

            if (param is not null and string command)
            {
                if (command.Contains('@'))
                {
                    string[] commands = command.Split('@');
                    foreach (var _command in commands)
                    {
                        PowerPlantServer.Execute(simple(_command));
                        await Task.Delay(500);
                    }
                }
                else
                {
                    PowerPlantServer.Execute(simple(command));
                }
            }
        }

        //显示选中的指令信息
        public async void UnexpectedCmdInfoEcho(MvvmMessage message)
        {
            if (message.MsgBody is AlterCommandStruct alterInfo)
            {
                var alterCommand = new AlterCommandStruct(alterInfo.AlterCommand, alterInfo.AlterIndex);
                EchoCommandInfo = alterCommand;
                HoldOverSectionModel.CommandEchoisWalking = true;
                await CmdEchoOpacityGradent();
            }
        }
    }
}
